﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.APP.TimeAttentsService;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.BLL;

namespace KPIS.GERP.GHRMS.APP.App_UI.UserControls
{
    public partial class PS_TimeAttMonthly2 : System.Web.UI.UserControl
    {
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private ITimeAttendantsBLL timeBLL = new TimeAttendantsBLL();
        private TimeAttentsServiceClient taService = new TimeAttentsServiceClient();
        private SsMng ssMng = new SsMng();
        private const int ItemsPerRequest = 10;
        private object _dataItem = null;
        private Main main = new Main();
        protected bool IsUserControlPostBack
        {
            get
            {
                return this.ViewState["IsUserControlPostBack"] != null;
            }
        }

        public object DataItem
        {
            get
            {
                return this._dataItem;
            }
            set
            {
                this._dataItem = value;
            }
        }

        //Initializing the new variable updating ViewState data.
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void OnLoad(System.EventArgs e)
        { 
            if (DataItem != null)
            {
                bindYear();
                bindEmployee();
                bool isEdit = !(DataItem is Telerik.Web.UI.GridInsertionObject);

                if (isEdit)
                {
                    lblSeq.Text = DataBinder.Eval(DataItem, "TimeAttMonthId").ToString();
                    cmbEmployee.SelectedValue = cmbEmployee.Items.FindItemByValue(DataBinder.Eval(DataItem, "EmpId").ToString()).Value; 
                    radNtxPlanWorkingDay.Text = DataBinder.Eval(DataItem, "PlanWorkingDayCount").ToString().Replace("วัน", "").Trim();
                    radNtxWorkingDay.Text = DataBinder.Eval(DataItem, "ActualWorkingDayCount").ToString().Replace("วัน", "").Trim();
                    radNtxLateDay.Text = DataBinder.Eval(DataItem, "LateDayCount").ToString().Replace("วัน", "").Trim();
                    radNtxAbsenceValid.Text = DataBinder.Eval(DataItem, "LateDayCount").ToString().Replace("วัน", "").Trim();
                    radNtxNotWorkingDay.Text = DataBinder.Eval(DataItem, "NotWorkingDayCount").ToString().Replace("วัน", "").Trim();
                    radTxtRemark.Text = DataBinder.Eval(DataItem, "Remarks").ToString();
                    cmbForMonth.SelectedValue = cmbForMonth.Items.FindItemByText(DataBinder.Eval(DataItem, "WorkingMonth").ToString()).Value;
                    cmbForYear.SelectedValue = cmbForYear.Items.FindItemByValue(DataBinder.Eval(DataItem, "WorkingYear").ToString()).Value;
                }
                else
                {
                    // Case Insert 
                }

                btnUpdate.Visible = isEdit;
                btnAddnew.Visible = !isEdit;
                cmbEmployee.Enabled = !isEdit;
                cmbForMonth.Enabled = !isEdit;
                cmbForYear.Enabled = !isEdit;
                panel1.Visible = isEdit;
            }
        }

        private void bindEmployee()
        {
            cmbEmployee.Items.Clear();
            Nullable<int> nJobSite = main.ConvertNullInt(Session["JOBSITESEQ"]);
            string empType = Convert.ToString(Session["EMPTYPE"]);

            DataSet ds = empBLL.LoadEmployees(null, "" + empType, null, nJobSite, true, "");
            DataTable dt = ds.Tables[0];
              
            int j = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cmbEmployee.Items.Add(new RadComboBoxItem(dt.Rows[i]["FULL_NAME"].ToString(), dt.Rows[i]["EMP_SEQ"].ToString()));

                TableRow tr = new TableRow();
                TableCell tdPosRef = new TableCell();
                Label lblPosRef = new Label();
                lblPosRef.Text = dt.Rows[i]["FULL_NAME"].ToString();
                tdPosRef.Width = Unit.Pixel(150);
                tdPosRef.Controls.Add(lblPosRef);
                tr.Cells.Add(tdPosRef);

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["POS_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(100);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                TableCell tdClassSpecName = new TableCell();
                Label lblClassSpecName = new Label();
                lblClassSpecName.Text = dt.Rows[i]["CLASS_NAME"].ToString();
                tdClassSpecName.Width = Unit.Pixel(100);
                tdClassSpecName.Controls.Add(lblClassSpecName);
                tr.Cells.Add(tdClassSpecName);

                TableCell tdJobName = new TableCell();
                Label lblJobName = new Label();
                lblJobName.Text = dt.Rows[i]["JOB_SITE_NAME"].ToString();
                tdJobName.Width = Unit.Pixel(150);
                tdJobName.Controls.Add(lblJobName);
                tr.Cells.Add(tdJobName);

                ((Table)cmbEmployee.Items[j].FindControl("tableEmployee")).Controls.Add(tr);
                j++;
            } 
        }

        private void bindYear()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            for (int i = 2500; i <= 2600; i++)
            {
                var r = dt.NewRow();
                r["Name"] = i; 

                dt.Rows.Add(r);
            }
            cmbForYear.DataSource = dt;
            cmbForYear.DataBind();
            cmbForYear.SelectedValue = DateTime.Today.ToString("yyyy", new CultureInfo("th-TH"));
        } 

        protected void btnAddnew_Click(object sender, EventArgs e)
        {
            var tams = taService.ListPsTimeAttendanceMonthlies().Where(o1=>o1.RecordStatus != "D").ToList();
            if (tams.Any(o1 => o1.EmpId == Convert.ToInt32(cmbEmployee.SelectedValue) &&
                           o1.WorkingMonth == Convert.ToInt32(cmbForMonth.SelectedValue) &&
                           o1.WorkingYear == Convert.ToInt32(cmbForYear.SelectedValue) - 543))
            {
                main.MessageAlert(Page, "มีสรุปการปฎิบัติงานสำหรับเจ้าหน้าที่คนนี้ในเดือนนี้แล้ว ให้คลิกแก้ไขที่รายการนั้นๆ แทน");
                return;
            }

            var o = new PsTimeAttendanceMonthly();
            o.EmpId = Convert.ToInt32(cmbEmployee.SelectedValue);
            o.WorkingMonth = Convert.ToInt32(cmbForMonth.SelectedValue);
            o.WorkingYear = Convert.ToInt32(cmbForYear.SelectedValue) - 543;
            o.PlanWorkingDayCount = main.ConvertDefaultInt(radNtxPlanWorkingDay.Value);
            o.ActualWorkingDayCount = main.ConvertDefaultInt(radNtxWorkingDay.Value);
            o.ValidAbsenceDayCount = main.ConvertDefaultInt(radNtxAbsenceValid.Value);
            o.LateDayCount = main.ConvertDefaultInt(radNtxLateDay.Value);
            o.NotWorkingDayCount = main.ConvertDefaultInt(radNtxNotWorkingDay.Value);
            o.Remarks = radTxtRemark.Text;
            o.RecordStatus = "U";
            o.CreatedBy = new SsMng().EmpSeqI;
            o.CreatedWhen = DateTime.Now;
            taService.InsertPsTimeAttendanceMonthly(o);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            var o = new PsTimeAttendanceMonthly();
            o.TimeAttMonthId = Convert.ToInt32(lblSeq.Text);
            o.EmpId = Convert.ToInt32(cmbEmployee.SelectedValue);
            o.WorkingMonth = Convert.ToInt32(cmbForMonth.SelectedValue);
            o.WorkingYear = Convert.ToInt32(cmbForYear.SelectedValue) - 543;
            o.PlanWorkingDayCount = main.ConvertDefaultInt(radNtxPlanWorkingDay.Value);
            o.ActualWorkingDayCount = main.ConvertDefaultInt(radNtxWorkingDay.Value);
            o.ValidAbsenceDayCount = main.ConvertDefaultInt(radNtxAbsenceValid.Value);
            o.LateDayCount = main.ConvertDefaultInt(radNtxLateDay.Value);
            o.NotWorkingDayCount = main.ConvertDefaultInt(radNtxNotWorkingDay.Value);
            o.Remarks = radTxtRemark.Text;
            o.RecordStatus = "U";
            o.CreatedBy = new SsMng().EmpSeqI;
            o.CreatedWhen = DateTime.Now;
            taService.UpdatePsTimeAttendanceMonthly(o);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {

        }
    }
}